using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Collections.Generic ;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using HermesPortal.Core;  
public partial class Realms_Controls_RealmsTreeView : System.Web.UI.UserControl
{

  
    public int SagaID
    {
        get
        {
            return ((PageBase)this.Page).SagaID;  
        }
    }
    public bool IsAdmin
    {
        get { return Roles.IsUserInRole(this.Page.User.Identity.Name, "sysAdmin"); }
    }
    public int CreatorID
    {
        get
        {
            return ((PageBase)this.Page).Creator.Id ; 
        }

    }
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            LoadTreeView();
            RealmView1.Visible = false;  
        }
    }

    private void LoadTreeView()
    {
        List<Realm> realms = null;
        if (IsAdmin)
            realms = RealmServices.AdminGetRealms(SagaID, 0);
        else
            realms = RealmServices.GetRealms(SagaID, 0, CreatorID);
        foreach (Realm realm in realms)
        {
            realmsTree.Nodes.Add(CreateNode(realm));
            
        }
    }

    private TreeNode CreateNode(Realm realm)
    {
        TreeNode node = new TreeNode();
        node.Text = realm.Title.Length > 30?realm.Title.Substring(0,30)+" ...": realm.Title;
        node.ToolTip = realm.Summary;
        node.Value = realm.RealmID.ToString() ;
        node.Checked = realm.IsPrivate;

        List<Realm> subRealms = null;
        if (IsAdmin)
        {
           subRealms =  RealmServices.AdminGetRealms(SagaID,realm.RealmID);
        }
        else
           subRealms = RealmServices.GetRealms(SagaID, realm.RealmID, CreatorID);
        
        // check if we have any sub realms if we do 
        //then need to check if the user can view them
       if ((subRealms.Count > 0) && (!realm.IsPrivate || (realm.CreatorID == CreatorID) || IsAdmin))
        {
            foreach (Realm subRealm in subRealms)
            node.ChildNodes.Add( CreateNode(  subRealm)); 
        }
        return node; 
    }

    protected void  SelectedNodeChange( object source, EventArgs e)
    {
        TreeNode node = realmsTree.SelectedNode;
        RealmView1.IsSummary = true;  
        RealmView1.RealmID =Convert.ToInt32 ( node.Value);
        RealmView1.SagaID = SagaID;
        RealmView1.BindControls();
        RealmView1.Visible = true;  
  
    }
}
